package com.sample.base

import android.content.Intent
import android.graphics.drawable.BitmapDrawable
import android.text.TextUtils
import android.util.Log
import androidx.core.content.ContextCompat
import com.loyal.client.impl.RxSubscriberListener
import com.loyal.dialog.LoadingDialog
import com.loyal.helper.PermissionHelper
import com.loyal.kit.LogUtil
import com.loyal.rx3.RxUtil
import com.sample.base.base.BaseActivity
import com.sample.base.databinding.ActivityMainBinding
import com.sample.base.rxjava.RxJavaTaskSubscriber
import com.sample.base.rxjava.RxProgressSubscriber
import com.sample.base.ui.activity.*
import okhttp3.ResponseBody
import java.io.File

class MainActivity : BaseActivity(), RxSubscriberListener<String?> {
    private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun setLayoutOrView() {
        setContentView(binding.root)
    }

    override fun afterOnCreate() {
        binding.dialog.setOnClickListener {
            startAct(DialogActivity::class.java)
        }
        binding.drawer.setOnClickListener {
            startAct(DrawerActivity::class.java)
        }
        binding.permission.setOnClickListener { startAct(PermissionActivity::class.java) }
        binding.recycle.setOnClickListener { startAct(RecyclerViewActivity::class.java) }
        binding.downLoad.setOnClickListener { download() }
        binding.compare.setOnClickListener { compare() }
        binding.vb.setOnClickListener { startAct(VBActivity::class.java) }
        binding.toolbarMenu.setOnClickListener { startAct(ToolbarMenuActivity::class.java) }
        binding.bar.setOnClickListener { startAct(BarActivity::class.java) }
        binding.full.setOnClickListener { startAct(FullScreenActivity::class.java) }
        binding.loading.setOnClickListener {
            val progress = LoadingDialog.show(this, "", "测试")
            progress.setCancelable(true)
            progress.setCanceledOnTouchOutside(true)
            progress.setFullScreen(isFullScreen)
            progress.show()
            progress.setOnShowListener {

            }
        }
    }

    private fun startAct(clazz: Class<*>) {
        startActivity(Intent(this, clazz))
    }

    private fun download() {
        showDialog("开始下载")
        val subscriber: RxProgressSubscriber<ResponseBody> = RxProgressSubscriber(this)
        val url = "http://192.168.0.110:8080/mwm/action.do?method=doShowIconByIO&account=loyal"
        subscriber.setSubscribeListener(object : RxSubscriberListener<ResponseBody> {
            override fun onResult(what: Int, tag: Any?, responseBody: ResponseBody) {
                try {
                    val iconFile = File(FileUtil.imagePath, "icon_$tag.jpg")
                    FileUtil.deleteFile(iconFile)
                    val save = ImageUtil.saveToFile(iconFile, responseBody.byteStream())
                    LogUtil.e("", if (TextUtils.isEmpty(save)) "下载失败" else "保存成功")
                } catch (e: Exception) {
                    Log.e("onResult: ", "imageService::Error--", e)
                    onError(what, tag, e)
                }
            }

            override fun onError(what: Int, tag: Any?, e: Throwable) {
                println("downLoad$e")
            }
        })
        RxUtil.rxExecuteAndCompute(subscriber.downloadImage(url), subscriber)
    }

    private fun compare() {
        if (!PermissionHelper.checkPermission(this, PermissionHelper.WRITE_EXTERNAL_STORAGE)) {
            showDialog("未授予存储权限！")
            return
        }

        val bitmap = ContextCompat.getDrawable(this, R.mipmap.pic) as BitmapDrawable? ?: return
        val subscriber = RxJavaTaskSubscriber<String>(this)
        subscriber.showProgressDialog(true).setDialogMessage("照片压缩中...")
        subscriber.setSubscribeListener(object : RxSubscriberListener<String?> {
            override fun onResult(what: Int, tag: Any?, result: String?) {
                showToast(if (TextUtils.isEmpty(result)) "失败" else "成功")
            }

            override fun onError(what: Int, tag: Any?, e: Throwable) {
                showErrorDialog("压缩失败", e)
            }
        })
        RxUtil.rxExecuteAndCompute(
            subscriber.saveBmp(FileUtil.imagePath + "pic.jpg", bitmap.bitmap), subscriber
        )
    }

    override fun onResult(what: Int, tag: Any?, result: String?) {
        try {
            Log.e("onResult: ", "" + result)
        } catch (e: Exception) {
            e.printStackTrace()
            onError(what, tag, e)
        }
    }

    override fun onError(what: Int, tag: Any?, e: Throwable) {
        showErrorDialog("Error", e)
    }

    override fun onStop() {
        super.onStop()
        Log.e("onStop: ", "MainActivity")
    }
}